package com.open.demo.flow

import android.os.Bundle
import android.util.Log
import androidx.activity.compose.setContent
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material.Button
import androidx.compose.material.Text
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import com.open.demo.bean.Data
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.launch

class FlowActivity : AppCompatActivity() {

    val uiState = MutableStateFlow<String>("")

    companion object {
        const val TAG = "Flow Demo"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            Box(
                modifier = Modifier.fillMaxSize(),
                contentAlignment = Alignment.Center
            ) {
                Button(onClick = {
                    val testFlow = flow<String>{
                        emit("hello")
                        emit("flow")
                    }
                    GlobalScope.launch {
                        testFlow.collect{ value->
                            Log.d(TAG, "value:${value}")
                        }
                        uiState.emit("Hello Flow")
                    }
                    uiState.value = "520"
                }) {
                    Text(text = "点击测试DEMO")
                }
            }
        }
        //
        GlobalScope.launch {
            testUiState()
        }
    }

    suspend fun testUiState() {
        uiState.collect { value->Log.d(TAG, "value:${value}") }
    }
}